﻿using gudusoft.gsqlparser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mysoft.QuickCode.DAL
{
    internal class MSSQLParser
    {
        private TSelectSqlStatement tsss = null;
        private string _sqlText;
        public string SqlText
        {
            set
            {
                _sqlText = value;

                //SQL文本发生改变，则重新解析
                TGSqlParser sqlParser = new TGSqlParser(TDbVendor.DbVMssql);
                sqlParser.SqlText.Text = _sqlText;
                sqlParser.Parse();
                tsss = sqlParser.SqlStatements.First() as TSelectSqlStatement;
            }
            get
            {
                return _sqlText;
            }
        }

        public MSSQLParser()
        {
        }
        public MSSQLParser(string sql)
        {
            this.SqlText = sql;
        }

        /// <summary>
        /// 获取取分页数据的SQL语句
        /// </summary>
        /// <param name="pageNum">当前页码：从 1 开始</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="orderByText">排序字段</param>
        /// <returns></returns>
        public string GetSqlPager(int pageNum = 1, int pageSize = 10, string orderByText = "")
        {
            string sqlPager = string.Format(@"select top {0} 
        * 
from    ( select    {1} ,
                    row_number() over ( order by {5} ) _Row_Number_
          from      {2}
          where     {3}
        ) t
where   t.[_Row_Number_]>{4}
order by t.[_Row_Number_] asc",
                pageSize,
                tsss.SelectClauseText,
                tsss.FromClauseText,
                string.IsNullOrEmpty(tsss.WhereClauseText) ? "1=1" : tsss.WhereClauseText,
                (pageNum - 1) * pageSize,
                string.IsNullOrEmpty(orderByText) ? tsss.SortClauseText : orderByText);

            return sqlPager;
        }

        /// <summary>
        /// 获取计算记录总数的SQL语句
        /// </summary>
        /// <returns></returns>
        public string GetSqlCount()
        {
            string sqlCount = string.Format(@"select count(1) from {0} where {1}",
                tsss.FromClauseText,
                string.IsNullOrEmpty(tsss.WhereClauseText) ? "1=1" : tsss.WhereClauseText);

            return sqlCount;
        }
    }
}
